﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SSharing.Frameworks.NetCore.Common.Extends;
using SSharing.Frameworks.NetCore.Common.Results;

namespace KwaiXiaoDian.OpenApi.Middlewares
{
    /// <summary>
    /// IP白名单中间件
    /// </summary>
    public class IpWhitelistMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="configuration"></param>
        public IpWhitelistMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            var whitelist = new string[] { };

            var clientIp = context.Connection.RemoteIpAddress.ToString();
            var ipWhitelistStr = _configuration["IpWhitelist"];
            if (!ipWhitelistStr.IsNullOrEmpty())
            {
                whitelist = ipWhitelistStr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (whitelist.HasValue() && !whitelist.Contains(clientIp))
            {
                context.Response.StatusCode = StatusCodes.Status200OK;
                await context.Response.WriteAsJsonAsync<ApiResult>(new ApiResult
                {
                    ErrorCode = "B0102",
                    ErrorMessage = "请求过于频繁，请稍后再试！"
                });
                return;
            }

            await _next(context);
        }
    }
}
